package com.invengo.module_robot.ui.fragment.advert;

import android.annotation.SuppressLint;
import android.app.Application;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;

import com.blankj.utilcode.util.ImageUtils;
import com.invengo.base.http.RobotRxUtils;
import com.invengo.library_orionstar.ActionEvent;
import com.invengo.library_db.entity.module_robot.ActivitBean;
import com.invengo.library_orionstar.SpeechEvent;
import com.invengo.module_robot.BR;
import com.invengo.module_robot.R;
import com.invengo.module_robot.data.entity.AdvertBean;
import com.invengo.module_robot.data.repsitory.RobotRepsitory;
import com.invengo.module_robot.ui.fragment.advert.item.ViewPagerItemViewModel;
import com.invengo.module_robot.ui.fragment.popular.item.PopularItemViewModel;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.tatarka.bindingcollectionadapter2.BindingViewPagerAdapter;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import okhttp3.ResponseBody;

public class AdvertViewModel extends BaseViewModel<RobotRepsitory> {
    public SingleLiveEvent<String> tipContent = new SingleLiveEvent<>();
    public BindingViewPagerAdapter adapter = new BindingViewPagerAdapter() {
        @Override
        public float getPageWidth(int position) {
            return 0.98f;
        }
    };

    //给ViewPager添加ObservableList
    public ObservableList<ViewPagerItemViewModel> items = new ObservableArrayList<>();
    //给ViewPager添加ItemBinding
    public ItemBinding<ViewPagerItemViewModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_advert);

    //给ViewPager添加ObservableList

    public AdvertViewModel(@NonNull Application application) {
        super(application, RobotRepsitory.getInstance());
//        test();
    }

    /**
     * 获取广告
     */
    public void getAdvert() {
        if (items.size() == 0) {
            getUC().getShowRobotLoadingEvent().call();
            model.getActivities()
                    .compose(RobotRxUtils.applySchedulers(getLifecycleProvider(), this, false))
                    .subscribe(activitBean -> {
                        loadImages(activitBean.getItems());
                    });
        } else {
            ui.finishLoadDataEvent.postValue(items.size());
        }
    }

    /**
     * 加载图像
     *
     * @param beans 豆
     */
    private void loadImages(List<ActivitBean.ItemsDTO> beans) {
        for (ActivitBean.ItemsDTO bean : beans) {
            Observable.just(bean)
                    .subscribeOn(Schedulers.io())
                    .map(itemsDTO -> {
                        AdvertBean bean1 = new AdvertBean();
                        bean1.setTitle(itemsDTO.getActivity().getRemark());
                        bean1.setUrl(itemsDTO.getActivity().getAddress());
                        bean1.setDrawable(model.getActivityImage(itemsDTO.getActivity().getAttachmentId()).subscribeOn(Schedulers.io()).map((Function<ResponseBody, Drawable>) body -> ImageUtils.bytes2Drawable(body.bytes())).blockingSingle());
                        return bean1;
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(bean12 -> {
                        items.add(new ViewPagerItemViewModel(AdvertViewModel.this, bean12));
                    });
        }
        getUC().getHideRobotLoadingEvent().call();
        ui.finishLoadDataEvent.postValue(beans.size());
    }


    public UIChangeObservable ui = new UIChangeObservable();


    private boolean moveFinish = false;

    /**
     * 设置移动完成
     *
     * @param moveFinish 移动完成
     */
    public void setMoveFinish(boolean moveFinish) {
        this.moveFinish = moveFinish;
    }

    public class UIChangeObservable {
        public SingleLiveEvent<Integer> changeCurrentEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<Integer> finishLoadDataEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<Void> launchMain = new SingleLiveEvent<>();
        public SingleLiveEvent<SingleLiveEvent<AdvertBean>> itemClickEvent = new SingleLiveEvent<>();
    }

    private int currentPosition2 = 0;
    private boolean isMoveNext = true;
    /**
     * 状态变化
     */
    public BindingCommand<Integer> StateChange = new BindingCommand<Integer>(state -> {
    });
    /**
     * 已选择页面
     */
    public BindingCommand<Integer> pageSelected = new BindingCommand<>(position -> {
        currentPosition2 = position;
        if (currentPosition2 == items.size() - 1)
            isMoveNext = false;
        else if (currentPosition2 == 0)
            isMoveNext = true;
        KLog.e(isMoveNext + "   " + items.size() + "  " + currentPosition2);
    });

    /**
     * 下水总管
     */
    public BindingCommand launchMain = new BindingCommand(() -> {
        getUC().getFinishActivityEvent().call();
    });

    /**
     * 回去
     */
    public BindingCommand goBack = new BindingCommand(() -> {
        getUC().getOnBackPressedEvent().call();
    });


    /**
     * 动作命令
     */
    public BindingCommand<ActionEvent> actionCommand = new BindingCommand<>(action -> {
        Observable.just(action)
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(event -> {
                    int position = 0;
                    switch (action.getEvent()) {
                        case ActionEvent.ACTION_DOWN:
                            if (currentPosition2 < items.size() - 1) {
                                ui.changeCurrentEvent.postValue(currentPosition2 + 1);
                            } else {
                                Messenger.getDefault().send(SpeechEvent.answer("没有更多的活动了！"), "SPEECH_TO_PAGE");
                            }
                            break;
                        case ActionEvent.ACTION_UP:
                            if (currentPosition2 > 0) {
                                ui.changeCurrentEvent.postValue(currentPosition2 - 1);
                            } else {
                                Messenger.getDefault().send(SpeechEvent.answer("没有更多的活动了！"), "SPEECH_TO_PAGE");
                            }
                            break;
                        case ActionEvent.ACTION_INFO:
                            KLog.e("了解详情。。。。");
                            ui.itemClickEvent.setValue(items.get(currentPosition2).bean);
                            break;
                        case ActionEvent.ACTION_CHANGE:
                            KLog.e(isMoveNext + "  xxx  " + currentPosition2);
                            if (isMoveNext) {
                                if (currentPosition2 < items.size() - 1) {
                                    ui.changeCurrentEvent.postValue(currentPosition2 + 1);
                                } else {
                                    Messenger.getDefault().send(SpeechEvent.answer("没有更多的活动了！"), "SPEECH_TO_PAGE");
                                }
                            } else {
                                if (currentPosition2 > 0) {
                                    ui.changeCurrentEvent.postValue(currentPosition2 - 1);
                                } else {
                                    Messenger.getDefault().send(SpeechEvent.answer("没有更多的活动了！"), "SPEECH_TO_PAGE");
                                }
                            }
                            break;
                    }
                });
    });


    /**
     * search命令
     */
    public BindingCommand<String> searchCommand = new BindingCommand<>(question -> {

        Observable.just(question)
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    KLog.e("xxxxx");
                    searchList(s);
                });
    });

    /**
     * 搜索列表
     *
     * @param keyWord 关键词
     */
    @SuppressLint("NewApi")
    private void searchList(String keyWord) {
        Optional<ViewPagerItemViewModel> first = items.stream().filter(b -> {
            AdvertBean bean =b.bean.getValue();
            return !TextUtils.isEmpty(bean.getTitle())&&bean.getTitle().equals(keyWord);
                })
                .findFirst();
        if (first.isPresent()) {
            KLog.e("搜索有相同活动。。。");
            Messenger.getDefault().send(SpeechEvent.answer("好的！"), "SPEECH_TO_PAGE");
            ui.itemClickEvent.setValue(first.get().bean);
        } else {
            KLog.e("搜索没有结果。。。");
            Messenger.getDefault().send(SpeechEvent.answer("列表中没有该活动！"), "SPEECH_TO_PAGE");
        }
    }
}
